import { FC, Ref, useEffect, useRef, useState } from 'react';
import './index.less';
import * as echarts from 'echarts';
import { sheetOpt } from './option';
import { useStores } from '@/stores';
import { flawMapT, RowFlawInfoBackT } from '@/typings/global';
import { observer } from 'mobx-react-lite';
import { getRowFlawInfoBack } from '@/api/lot-detail-page';
import { runInAction } from 'mobx';
import { getEchartAxis } from '@/utils/tool';
import { UNIT_TO_M } from '@/utils/constant';

interface ChartsOptionConf {
  onRef: Ref<unknown> | undefined;
  onSubmit?: (sheetId: any, flawUid) => void;
}
const SheetFlawMap: FC<ChartsOptionConf> = (chartsProps: ChartsOptionConf) => {
  const [option, setOption] = useState<any>(sheetOpt);
  const { lotStore } = useStores();
  const myChartRef = useRef<echarts.ECharts>();
  const canvasRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    initChart();
  }, []);

  const initChart = () => {
    const canvasDom = canvasRef.current;
    if (canvasDom) {
      myChartRef.current = echarts.init(canvasDom);
      const opt = { ...option };
      setOption(opt);
      myChartRef.current?.setOption(opt);
      myChartRef.current?.on('click', function (params) {
        const flawData = params.data as RowFlawInfoBackT;
        const commitParam = {
          lotId: lotStore.lotId,
          layerId: lotStore.layerId,
          sheetId: flawData.sheetId,
          uid: flawData.uid,
          station: flawData.station
        };
        getRowFlawInfoBack(commitParam).then(flawDetails => {
          runInAction(() => {
            lotStore.card.detailShowDialog = true;
            lotStore.card.detailFlawRow = flawDetails.data;
          });
        });
      });
    }
  };

  useEffect(() => {
    try {
      const opt = { ...option };
      let data = [] as any;
      if (lotStore?.sheetFlawMapOption?.flaws && lotStore?.sheetFlawMapOption?.flaws.length) {
        data = JSON.parse(JSON.stringify(lotStore?.sheetFlawMapOption?.flaws));
        data = data.map(item => {
          item.value[1] = item.value[1] * UNIT_TO_M;
          return item;
        });
      }
      //  console.log('片上的缺陷:过滤是全局缺陷之内的缺陷，才是', data);
      //  console.log('这个片的信息:', lotStore.sheet.sheetInfo);
      const { doffCd, doffMd, lengthCd, lengthMd } = lotStore.sheet.sheetInfo;
      const sheetOptMinMax = getEchartAxis(flawMapT.sheet, doffCd, doffMd, lengthCd, lengthMd);
      
      opt.xAxis[0].min = sheetOptMinMax.xMin;
      opt.xAxis[0].max = sheetOptMinMax.xMax;
      opt.yAxis.min = sheetOptMinMax.yMin;
      opt.yAxis.max = sheetOptMinMax.yMax;
      opt.xAxis[0]['interval'] = (sheetOptMinMax.xMax - sheetOptMinMax.xMin) / 5; // 划分成5等份
      opt.yAxis['interval'] = (sheetOptMinMax.yMax - sheetOptMinMax.yMin) / 5; // 划分成5等份

      //   // 计算x轴的最大值和y轴的最大值,以1为刻度
      //   const maxAxios = data.reduce(
      //     (Axios, item) => {
      //       if (item.value[0] > Axios.maxXAxios) {
      //         Axios.maxXAxios = item.value[0];
      //       }
      //       if (item.value[1] > Axios.maxYAxios) {
      //         Axios.maxYAxios = item.value[1];
      //       }
      //       return Axios;
      //     },
      //     { maxXAxios: 0, maxYAxios: 0 }
      //   );
      //   console.log('计算片---，最大轴最小轴，', maxAxios);

      //   // 如果最大x轴值大于y轴值就互换
      //   if (maxAxios.maxXAxios > maxAxios.maxYAxios) {
      //     opt.xAxis[0].max = Math.ceil(maxAxios.maxYAxios);
      //     opt.yAxis.max = Math.ceil(maxAxios.maxXAxios);
      //     data = data.map(item => {
      //       const [a, b] = item.value;
      //       item.value = [b, a];
      //       return item;
      //     });
      //   } else {
      //     opt.xAxis[0].max = Math.ceil(maxAxios.maxXAxios);
      //     opt.yAxis.max = Math.ceil(maxAxios.maxYAxios);
      //   }

      opt.series[0].data = data;
      setOption(opt);
      myChartRef?.current?.setOption(opt, { notMerge: true });
    } catch (error) {
      console.log(error);
    }
  }, [lotStore.sheetFlawMapOption.flaws]);

  return (
    <div className="sheet-flaw-map">
      <div className="canvas-top">
        <ul className="descriptions-ul">
          <li>
            <span className="descriptions-ul-title">编号:</span>
            <span className="descriptions-ul-text">{lotStore.sheet.sheetId ? lotStore.sheet.sheetId : 0}</span>
          </li>
          <li>
            <span className="descriptions-ul-title">缺陷总数:</span>
            <span className="descriptions-ul-text">{lotStore.sheet.flawSum ? lotStore.sheet.flawSum : 0}</span>
          </li>
        </ul>
      </div>
      <div className="canvas" id="canvas" ref={canvasRef} />
    </div>
  );
};
export default observer(SheetFlawMap);
